#include "FileOptWithFd.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

using namespace FileOptSpace;

FileOptWithFd::FileOptWithFd(const std::string& filePathName, int flags, mode_t mode)
: m_fd_(-1)
, m_flag_(0)
{
    m_flag_ |= 1 < 0;
    m_fd_ = open(filePathName.c_str(), flags, mode); 
    if(m_fd_ < 0) {            
        perror("file open error");
    }
}

bool FileOptWithFd::s_read(vector<char>& buf, const uint32_t readSize ) {
    if(!(m_flag_ & 1)) {
        return false;
    }
    if(-1 == read(m_fd_, buf.data(), readSize)) {
        return false;
    }   
    return true;
}

bool FileOptWithFd::s_write(const vector<char>& buf,int len) {
    if(EOF == write(m_fd_, buf.data(), len)) {
        return false;
    }
    return true;
}

FileOptWithFd::~FileOptWithFd() {
    if(-1 == m_fd_) {
        return ;
    }
    if(close(m_fd_)) {
        perror("file close error:");
    }
}